package com.cnpc.iot.scgl.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnpc.framework.base.dao.BaseDao;
import com.cnpc.framework.base.entity.Dict;
import com.cnpc.iot.scgl.entity.Dfiled;
import com.cnpc.iot.scgl.entity.Pnode;
import com.cnpc.iot.scgl.service.PnodeService;

@Service
public class PnodeServiceImpl implements PnodeService {
	
	private static String F_VARCHAR = "VARCHAR";
	private static String F_LONG = "LONG";
	private static String F_DATETIME = "DATETIME";
	private static String F_DATEPICK = "DATEPICK";

    @Autowired
    private BaseDao baseDao;

    @Override
    public boolean syncTable(Pnode pnode) {
        List<Dfiled> flist = baseDao.find("from Dfiled where nodeId='"+pnode.getId()+"' order by orderId");
        if(null != flist && flist.size() > 0){
            String sql = createSql(pnode, flist);
            try {
				baseDao.executeSql(sql);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
        }else{
            return false;
        }
    }

    private String createSql(Pnode pnode, List<Dfiled> flist){
        StringBuffer sb = new StringBuffer("CREATE TABLE dny_");
        sb.append(pnode.getCode() + " ( ");
        sb.append("id varchar(36) NOT NULL,  ");
        sb.append("parent varchar(36) DEFAULT NULL, ");
        sb.append("creater varchar(50) DEFAULT NULL, ");
        sb.append("optime datetime DEFAULT NULL, ");
        sb.append("fileids varchar(500) DEFAULT NULL, ");
        for(int i=0; i<flist.size();i++){
        	Dfiled f = flist.get(i);
        	sb.append(f.getCode()+" ");
        	Dict dict = baseDao.get(Dict.class, f.getFtype());
            if(dict.getCode().equals(F_VARCHAR)) {
            	sb.append("varchar("+f.getFlength()+") DEFAULT NULL,");
            }else if(dict.getCode().equals(F_LONG)) {
            	sb.append("bigint("+f.getFlength()+") DEFAULT NULL,");
            }else if(dict.getCode().equals(F_DATETIME) || dict.getCode().equals(F_DATEPICK)) {
            	sb.append("datetime DEFAULT NULL,");
            }
        }
        sb.append("PRIMARY KEY (id)");
        sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        System.out.println(sb.toString());
        return sb.toString();
    }
}
